#include <iostream>
#include <functional>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <csignal>

class ThreadPool {
public:
    ThreadPool(size_t numThreads) : stop(false) {
        for (size_t i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(queueMutex);
                        condition.wait(lock, [this] { return stop || !taskQueue.empty(); });
                        if (stop && taskQueue.empty())
                            return;
                        task = std::move(taskQueue.front());
                        taskQueue.pop();
                    }
                    task();
                }
            });
        }
    }

    template <class F, class... Args>
    void enqueue(F&& f, Args&&... args) {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            taskQueue.emplace([f, args...] { f(args...); });
        }
        condition.notify_one();
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread& worker : workers)
            worker.join();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> taskQueue;
    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;
};

// 示例任务函数
void taskFunction(int id) {
    std::cout << "Task " << id << " is being executed." << std::endl;
    // 这里可以插入具体的任务逻辑
}

int computeTask()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "computeTask has been complete" << std::endl;
    return 1;
}

std::atomic_bool exitFlag(false);
// Signal handler function to handle the SIGINT signal (Ctrl+C)
void signalHandler(int signal)
{
    if (signal == SIGINT)
    {
        std::cout << "SIGINT received. Exiting the program gracefully." << std::endl;
        exitFlag.store(true,std::memory_order_release);
    }
}

void eventHandler()
{
    // Simulating an event
    std::cout << "Event occurred!" << std::endl;
}


int main() {
    // 创建一个具有4个线程的线程池
    ThreadPool pool(4);

    // 将任务提交给线程池执行
    for (int i = 0; i < 10; ++i) {
        pool.enqueue(taskFunction, i);
    }

    pool.enqueue(computeTask);

    // 等待所有任务完成
    while (!exitFlag.load(std::memory_order_acquire))
    {
        // Check for events and handle them
        eventHandler();

        // Simulating some other work
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    return 0;
}
